import axios from 'axios'

// axios 全局配置
axios.defaults.timeout = 30000
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
axios.defaults.baseURL = 'http://www.tong-hui.cc/API'

//请求拦截器
axios.interceptors.request.use((config) => {
    //在发送请求之前做某事
    return config
}, (err) => {
    return Promise.reject(err)
})

//响应拦截器
axios.interceptors.response.use((response) => {
    //对响应数据做些事
    return response
}, (err) => {
    return Promise.reject(err)
})

export function $http(url, params) {
    return new Promise((resolve, reject) => {
        axios.get(url, params).then(response => {
            resolve(response)
        }).catch(function(err) {
            if (err.response) {
                switch (err.response.status) {
                    case 404:
                        alert(`所请求的页面不存在或已被删除: ${err.response.config.url}`)
                        break
                    default:
                        alert('服务器未响应，请重试');
                }
            } else {
                alert('网络异常，请重试')
                return false
            }
        })
    })
}

//API
export default {
    GetHeader(params) {
        return $http('?header', params)
    },
    GetHome(params) {
        return $http('?home', params)
    },
    GetProductList(params) {
        return $http('?product_list', params)
    },
    GetProductView(params) {
        return $http('?product_view', params)
    },
    GetMiniCart(params) {
        return $http('?mini_cart', params)
    },
    GetCartItem(params) {
        return $http('?cart', params)
    }
}